/*
 * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.templateproject.fragment.camera;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
//import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xuexiang.templateproject.MyApp;
import com.xuexiang.templateproject.activity.CameraViewActivity;
import com.xuexiang.templateproject.activity.MatchActivity;
import com.xuexiang.templateproject.adapter.ImageItemAdapter;
import com.xuexiang.templateproject.bean.BoxForDLS;
import com.xuexiang.templateproject.bean.ImageBoxEntity;
import com.xuexiang.templateproject.bean.ImageEntity;
import com.xuexiang.templateproject.bean.Question;
import com.xuexiang.templateproject.bean.QuestionForDLS;
import com.xuexiang.templateproject.core.BaseFragment;
import com.xuexiang.templateproject.databinding.FragmentCameraBinding;
import com.xuexiang.templateproject.fragment.home.HomeFragment;
import com.xuexiang.templateproject.utils.OssUtils;
import com.xuexiang.templateproject.utils.PicUtils;
import com.xuexiang.templateproject.utils.TokenUtils;
import com.xuexiang.templateproject.widget.showLoadingDialog;
import com.xuexiang.xaop.annotation.DiskCache;
import com.xuexiang.xaop.annotation.IOThread;
import com.xuexiang.xaop.annotation.MainThread;
import com.xuexiang.xaop.annotation.MemoryCache;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xui.widget.actionbar.TitleBar;

import static android.app.Activity.RESULT_OK;
import static com.xuexiang.templateproject.activity.PictureCropActivity.KEY_PICTURE_PATH;
import static com.xuexiang.xutil.XUtil.runOnUiThread;

import com.xuexiang.templateproject.R;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.common.logger.Logger;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import com.xuexiang.xhttp2.utils.RxSchedulers;
import com.xuexiang.xutil.display.ImageUtils;
import com.xuexiang.xutil.tip.ToastUtils;

/**
 * @author xuexiang
 * @since 2019-10-16 10:25
 */
@Page(name = "搜题", extra = R.drawable.ic_expand_camera)
public class CameraFragment extends BaseFragment<FragmentCameraBinding> implements View.OnClickListener{
    public static final int REQUEST_CODE_OPEN_CAMERA = 1245;
    public static final int REQUEST_CODE_PICTURE_CROP = 1122;

    List<String> mList = new ArrayList<String>();
    ImageItemAdapter imageItemAdapter;
    String QAA = "";
//    String mImagePath="";
//    CardAdapter mCardAdapter;
    @Override
    protected FragmentCameraBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentCameraBinding.inflate(inflater, container, attachToRoot);
    }
//    @Override
//    protected TitleBar initTitle() {
//        return null;
//    }
    @MainThread
    private void updateImg(Bitmap bitmap){
        Glide.with(MyApp.getContext()).load(bitmap).into(binding.ivContent);
    }
    @MainThread
    private void updateRecyclerview(List<ImageEntity> imageEntityList){
        Logger.d("updateRecyclerview "+imageEntityList.size());
        if(imageItemAdapter!=null) imageItemAdapter.setList(imageEntityList);

    }

    @Override
    protected void initViews() {


//        c.j(this.f1752e);

        imageItemAdapter = new ImageItemAdapter(R.layout.item_image_item,null);

        imageItemAdapter.setOnItemClickListener((adapter, view, position) -> {
            String imgPath = ((ImageItemAdapter)adapter).getItem(position).getFilePath();
            String imgOss = ((ImageItemAdapter)adapter).getItem(position).getImageOss();
            Logger.d("setOnItemChildClickListener "+imgOss);
            showLoadingDialog.showLoading(getContext());
            new Thread("io") {
                @Override
                public void run() {
                    boolean res =doUploadSearchQuestion(imgPath);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showLoadingDialog.hideLoading();
                        }
                    });
                    if(res){
//                        String json = new Gson().toJson(QAA);
                        MatchActivity.open(getActivity(),imgPath,QAA);

                    }
                }}.start();

        });
        binding.recyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.recyclerview.setAdapter(imageItemAdapter);
        CameraViewActivity.open(this);
    }
//    @Override
//    protected TitleBar initTitle() {
//        return null;
//    }
//    @Override
//    public void popToBack() {
//        popToBack("HomeFragment", null);
//    }
    @SingleClick
    @Override
    public void onClick(View view) {

    }

    String imgKey;
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_CODE_OPEN_CAMERA && resultCode == RESULT_OK) {
            if (data != null) {
                String imgPath = data.getStringExtra(KEY_PICTURE_PATH);
//                ImageLoader.get().loadImage(binding.ivContent, imgPath);
                showLoadingDialog.showLoading(getContext());
                new Thread("io") {
                    @Override
                    public void run() {
                        doUploadImageBoxx(imgPath);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showLoadingDialog.hideLoading();
                            }
                        });
                    }}.start();
            }
        }
    }

    @IOThread
    private boolean doUploadSearchQuestion(String imgPath){
        String imgKey = "souti_"+imgPath.hashCode();
        boolean ret = false;
        try {
            ret = OssUtils.uploadFile(imgPath,imgKey);
        } catch (ServiceException e) {
            throw new RuntimeException(e);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
       if(ret){
           QAA =searchQuestion(imgKey);
           if(QAA!=null){
               return true;
           }
       }else{
           ToastUtils.toast("上传图片失败。");
       }

//       return searchQuestion(imgKey);
        return false;
    }
    @IOThread
    private boolean doUploadImageBoxx(String imgPath){
        boolean ret = false;
        String imgKey = "saoti_"+imgPath.hashCode();
        try {
            ret = OssUtils.uploadFile(imgPath,imgKey);
        } catch (ServiceException e) {
            throw new RuntimeException(e);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
       if(ret){
           List<ImageEntity> imageEntityList = imgBox(imgKey);
           if(imageEntityList!=null){
               updateRecyclerview(imageEntityList);
               return true;
           }
       }else{
           ToastUtils.toast("上传图片失败。");
       }
       return ret;
    }
    @DiskCache(enableEmpty=false)
    @IOThread
    private  List<ImageEntity> imgBox(String imgKey){
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("imgURL", OssUtils.URI+imgKey)
                .build();
        Request request = new Request.Builder()
                .url("https://app.jiucuodashi.com/api/ai/imgBoxForDLS.do")
                .post(formBody)
                .build();
        Call call = client.newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException ignored) {
        } catch (RuntimeException e) {
            Logger.e(e.toString());
            ToastUtils.toast("框图失败。");
            return null;
        }
        Gson gson = new Gson();
        BoxForDLS boxForDLS=null;
        try {
            boxForDLS = gson.fromJson(response.body().string(),BoxForDLS.class );
        }
        catch (JsonSyntaxException | IllegalStateException | IOException e) {
            Logger.e(e.toString());
        }
        if(boxForDLS!=null){
            Logger.i("getErrMsg"+ boxForDLS.getErrMsg());
            Logger.i(boxForDLS.getErrCode());
            Logger.i("getSuccess"+boxForDLS.getSuccess());

            if(boxForDLS.getContent()!=null && boxForDLS.getContent().getHandRemoveImage()!=null){
                byte[] decodedString = Base64.decode(boxForDLS.getContent().getHandRemoveImage().split(",")[1], Base64.DEFAULT);
                Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
                List<BoxForDLS.BoxData> boxDataList = boxForDLS.getContent().getBoxData();
//                updateImg(decodedByte);
                if(boxDataList.size()>0){
                   List<ImageEntity> imageEntityList = new ArrayList<>();
                   for(int i = 0;i<boxDataList.size();i++){
                       List<Integer> boxdata =  boxDataList.get(i).getBox();
                       Rect rect = new Rect(boxdata.get(0),boxdata.get(1),boxdata.get(2),boxdata.get(3));
                       Bitmap bitmap = Bitmap.createBitmap(decodedByte, rect.left, rect.top, rect.width(), rect.height());
                       String imgpth = PicUtils.getImageSavePath();
                       ImageUtils.save(bitmap, imgpth, Bitmap.CompressFormat.JPEG);
                       ImageEntity imageEntity = new ImageEntity(imgpth);
                       imageEntity.setImageOss(imgKey+"i");
                       Logger.i("imageEntity "+i+" "+imageEntity.getFilePath());
                       Logger.i("getScore "+" "+boxDataList.get(i).getScore());
                        if(boxDataList.get(i).getScore()>0.4)
                       imageEntityList.add(imageEntity);
                  }
                   return imageEntityList;
//                    updateRecyclerview(imageEntityList);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            updateRecyclerview(imageEntityList);
//                        }
//                    });


                }
            }
        }
        ToastUtils.toast("框图失败。");
        return null;
    }
    @DiskCache(enableEmpty=false)
    @IOThread
    private String searchQuestion(String imgkey){
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("imgURL", OssUtils.URI+imgkey)
                .build();
        Request request = new Request.Builder()
                .url("https://app.jiucuodashi.com/api/ai/searchQuestionForDLS.do")
                .post(formBody)
                .build();
        Call call = client.newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Gson gson = new Gson();
        QuestionForDLS questionForDLS = null;
        try {
            questionForDLS = gson.fromJson(response.body().string(), QuestionForDLS.class);
        }
        catch (JsonSyntaxException | IllegalStateException | IOException e) {
            Logger.e(e.toString());
        }
        if(questionForDLS!=null){
            Logger.i(questionForDLS.getErrMsg());
            Logger.i(questionForDLS.getErrCode());
            Logger.i(questionForDLS.getSuccess());
            if(questionForDLS.getContent()!=null){
                List<Question> questionForDLSContentlist = questionForDLS.getContent();
               String json = new Gson().toJson(questionForDLSContentlist);
                return json;
            }
        }
        ToastUtils.toast("搜题失败。");
        return null;
    }



    private void textExtractionForDLS(String imgPath) {

        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("imgURL", imgPath)
                .build();
        Request request = new Request.Builder()
                .url("https://app.jiucuodashi.com/api/ai/textExtractionForDLS.do")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Logger.i("courses = "+response.body().string());
                assert response.body() != null;

            }
        });
    }


}
